package org.openurp.edu.student.info.web.action

import org.openurp.edu.student.info.model.Paystate
import java.{ util => ju }
import org.openurp.edu.student.info.model.Scholarship
import org.beangle.data.transfer.importer.listener.ImporterForeignerListener
import org.beangle.commons.lang.ClassLoaders
import org.openurp.edu.student.info.model.Schooling
import org.beangle.data.transfer.TransferListener
import org.openurp.edu.student.info.web.helper.ImportSchoolingListener
import org.openurp.edu.student.info.model.Paytype
import org.beangle.webmvc.entity.action.RestfulAction
import org.beangle.webmvc.api.view.View
import org.beangle.webmvc.api.view.Stream
import org.openurp.edu.student.info.web.helper.ExportExcelUtils
import java.io.OutputStream
import org.openurp.edu.student.info.model.Stdtype
import org.openurp.edu.student.info.model.HanZiStyle
import org.beangle.webmvc.api.annotation.mapping
import org.beangle.webmvc.api.annotation.param
import org.beangle.commons.lang.Numbers
import org.beangle.data.dao.OqlBuilder
import org.openurp.edu.student.info.model.Semester
import org.beangle.data.model.Updated
import org.beangle.webmvc.api.action.ServletSupport
import org.beangle.webmvc.api.annotation.response
import org.beangle.webmvc.api.view.Status
import org.openurp.edu.student.info.model.Student
import org.openurp.edu.student.info.model.Visa
import java.io.File
import org.openurp.edu.student.info.service.StudentPortraitService

/**
 * @author King Sun
 */
class PaymentAction extends RestfulAction[Schooling] with ImportDataSupport[Schooling] with ServletSupport {
  var studentPortraitService: StudentPortraitService = _
  override protected def indexSetting(): Unit = {
    put("semesters", entityDao.getAll(classOf[Semester]).sortBy { semester => semester.id })
    val semesterQuery = OqlBuilder.from(classOf[Semester], "semester").where(":now between semester.beginOn and semester.endOn", new java.util.Date())
    put("currentSemester", entityDao.search(semesterQuery).head)
  }

  override protected def editSetting(entity: Schooling): Unit = {
    put("stdtypes", entityDao.getAll(classOf[Stdtype]))
    put("paystates", entityDao.getAll(classOf[Paystate]))
    put("paytypes", entityDao.getAll(classOf[Paytype]))
    put("scholarships", entityDao.getAll(classOf[Scholarship]))
    put("semesters", entityDao.getAll(classOf[Semester]).sortBy { semester => semester.id })
    val semesterQuery = OqlBuilder.from(classOf[Semester], "semester").where(":now between semester.beginOn and semester.endOn", new java.util.Date())
    put("currentSemester", entityDao.search(semesterQuery).head)
  }

  override def search(): String = {
    put("math", new Math)
    super.search()
  }

  override protected def saveAndRedirect(schooling: Schooling): View = {
    if (schooling.paystate == null) {
      schooling.paystate = new Paystate
      schooling.paystate.id = 1L
    }
    schooling match {
      case updated: Updated => updated.updatedAt = new ju.Date()
      case _ =>
    }
    saveOrUpdate(schooling)
    redirect("edit", s"&id=${schooling.id}", "info.save.success")
  }

  def importTemplate: View = {
    Stream(ClassLoaders.getResourceAsStream("schooling.xls"), "application/vnd.ms-excel", "交费信息管理.xls")
  }

  protected override def importerListeners: List[_ <: TransferListener] = {
    List(new ImporterForeignerListener(entityDao), new ImportSchoolingListener(entityDao))
  }

  def exportpayment(): View = {
    val builder = this.getQueryBuilder()
    builder.limit(null)
    val list = collection.JavaConversions.asJavaCollection(entityDao.search(builder))
    //查出学生信息并放到map中
    val beans = new java.util.HashMap[String, Any]
    beans.put("list", list);
    //获得模板路径
    val path = ClassLoaders.getResourceAsStream("student_payment.xls");
    //准备输出流
    var os: OutputStream = null;
    response.setContentType("application/x-excel");
    response.setHeader("Content-Disposition", "attachment;filename=studentPay.xls");
    os = response.getOutputStream();
    ExportExcelUtils.excprtStudentExcel(beans, path, os);
    Status.Ok
  }

  @mapping(value = "{id}")
  override def info(@param("id") id: String): String = {
    val schoolings = entityDao.getAll(classOf[Schooling])
    val totalMap =
      if (schoolings.isEmpty) Map.empty else {
        schoolings.map(e => (e.id, HanZiStyle.build(Numbers.toInt(e.total)))).toMap
      }
    put("totalMap", totalMap)
    super.info(id)
  }
}

class Math {
  def parse(s: String): Double = {
    if (null == s) 0d
    else java.lang.Double.parseDouble(s)
  }
}
